<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="896" @ok="handleSubmit">
      <BasicForm @register="registerForm" @change="updateValue">

      </BasicForm>
  </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref} from 'vue';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import {formSchema} from '../DbGlfsc.data';
    import {saveOrUpdate} from '../DbGlfsc.api';
    import {defHttp} from "/@/utils/http/axios";
    import {apiCurrency} from "/@/views/assets/currency/Tblrate.api";
    import {api, dbCfzjbList, dbGlfb1List} from "/@/views/assets/leaseContract/DbHtb.api";
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate,updateSchema,getFieldsValue}] = useForm({
        labelWidth: 160,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 12}
    });
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        await resetFields();
        setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
            //表单赋值
            await setFieldsValue({
                ...data.record,
            });
            let temp = {...data.record};
          changeCurrency(temp.sfyf);
        }


      updateSchema([{field:"sfyf",componentProps:{
          onChange:changeCurrency,
          showTime:false,
          valueFormat:"YYYY-MM",
          getPopupContainer: () => document.body,
        }},{
            field:"jd",
        component:"Select",
        componentProps:{
              onChange:changeJDNR,
          options:[{label:"无",value:0},{label:"第一季度",value:1},{label:"第二季度",value:2},{label:"第三季度",value:3},{label:"第四季度",value:4}]
        }

        },
        { field: 'qymc', componentProps: {
            isRadioSelection:true,
            onChange:(d)=>{
              if(!d)
                updateSchema([ { field: 'htbh', componentProps: { options:[] } },]);

              const params = {mc:d,yxzt:'正常'};
              const res =  defHttp.get({url: api.list,params });
              res.then((data)=>{
                console.log(data);
                let option = [];
                for(let i=0;i<data.records.length;i++){
                  option.push({label:data.records[i].ph,value:data.records[i].ph});
                }
                updateSchema([ { field: 'htbh', componentProps: { options:option,
                  onChange:(e)=>{
                       console.log(e)
                       let params = {ph:e}
                       let res = dbGlfb1List(params);
                       console.log(res);
                       res.then((data)=>{
                         console.log(data)
                         let res2 = dbCfzjbList(params);
                         console.log(res2)
                         res2.then((data2)=>{
                           let cfzj = data2.records[0];
                           let td = data.records[0];

                           let fvt = {};
                           if(cfzj){
                             let cfzjtemp = {
                               cfzj:cfzj.dj,
                               jfmj:cfzj.jfmj,
                               pz4:cfzj.pz};
                             setFieldsValue(cfzjtemp);
                             fvt = Object.assign({},cfzjtemp)
                           }
                           if(td){
                             let tdtemp = {grgl:td.grgl,
                               pz1:td.pz1,
                               cfgl:td.cfgl,
                               cfmj:td.jfmj,
                               pz2:td.pz2,
                               wfbc:td.ttgl,
                               //jfbz:td.jsbz,
                               pz3:td.pz,
                             };
                           setFieldsValue(tdtemp);
                           fvt = Object.assign(fvt,tdtemp);
                           }
                           updatevaluebase(fvt);
                         })


                       });
                  }
                } },]);
              })
            },
          } },])


        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });

    function changeJDNR(e){
      let temp = "";
         if(e==1)
           temp = new Date().getFullYear()+"年"+"1月至"+new Date().getFullYear()+"年3月";
         if(e==2)
           temp = new Date().getFullYear()+"年"+"4月至"+new Date().getFullYear()+"年6月";
         if(e==3)
           temp = new Date().getFullYear()+"年"+"7月至"+new Date().getFullYear()+"年9月";
         if(e==4)
           temp = new Date().getFullYear()+"年"+"10月至"+new Date().getFullYear()+"年12月";
         setFieldsValue({jdnr:temp});
    }

    async function changeCurrency(e) {
      let params = {datein: e, cacode: "HKD"};
      let res = await defHttp.get({url: apiCurrency.list, params});
       console.log(res)
      if(res.records && res.records[0])
      await  setFieldsValue({currency: res.records[0].rate});
    }


    function updateValue(e){
      console.log("updateValue");
      const fv = getFieldsValue();
      updatevaluebase(fv);
    }


    function updatevaluebase(fv){
      console.log(fv);
      let grs = fv.grs?fv.grs:0;
      let grgl = fv.grgl?fv.grgl:0;
      let cfgl = fv.cfgl?fv.cfgl:0;
      let cfmj =  fv.cfmj?fv.cfmj:0;
      let wfbc = fv.wfbc?fv.wfbc:0;
      let jfbz = fv.jfbz?fv.jfbz:0;
      let cfzj = fv.cfzj?fv.cfzj:0;
      let jfmj = fv.jfmj?fv.jfmj:0;
      let qtfy = fv.qtfy?fv.qtfy:0;
      let currency = fv.currency?fv.currency:1;
      // console.log(currency);
      // console.log(grgl);
      // console.log(cfgl);
      // console.log(cfmj);
      // console.log(wfbc);
      // console.log(jfbz);
      // console.log(cfzj);
      // console.log(jfmj);
      // console.log(qtfy);
      let rzjs =0;
      let p1 = fv.pz1=='人民币'?grs*grgl:grs*grgl*currency;
      let p2 = fv.pz2=='人民币'?cfgl*cfmj:cfgl*cfmj*currency;
      let p3 = fv.pz3=='人民币'?wfbc*jfbz:wfbc*jfbz*currency;
      let p4 = fv.pz4=='人民币'?cfzj*jfmj:cfzj*jfmj*currency;
      let p5 = fv.pzQt=='人民币'?qtfy:qtfy*currency;
      // console.log(p1);
      // console.log(p2);
      // console.log(p3);
      // console.log(p4);
      // console.log(p5);
      rzjs = p1+p2+p3+p4+p5;
      //rzjs = p4+p5;
      let hzjs = fv.currency?rzjs/currency:0;
      // console.log(rzjs)
      let temp = Math.round(hzjs*100) / 100;
      let temp2 = Math.round(rzjs*100) / 100;

      setFieldsValue({rzjs:temp2.toFixed(0),hzjs:temp.toFixed(0)});
    };


    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
    //表单提交事件
    async function handleSubmit(v) {
        try {
            let values = await validate();
            setModalProps({confirmLoading: true});
            //提交表单
            await saveOrUpdate(values, isUpdate.value);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
</style>
